package com.stockz.ui.swing.charting.widget;

import javax.swing.DefaultComboBoxModel;

import org.springframework.aop.target.dynamic.Refreshable;
import org.springframework.core.Ordered;

import com.stockz.core.util.BarUtil.BarValueType;
import com.stockz.core.util.SpringUtil;
import com.stockz.ui.swing.charting.display.indicator.AbstractDisplayableIndicatorConfiguration;
import com.stockz.ui.swing.charting.util.RepaintStockChartPanelUtil;
import com.stockz.ui.swing.charting.view.StockChartPanel;
import com.stockz.ui.swing.widget.FilteredComboBox;
import com.stockz.ui.swing.widget.FilteredComboBox.OnSelectionCallback;

public class IndicatorComboBox extends FilteredComboBox implements
		OnSelectionCallback,Refreshable,Ordered {
	private static final long serialVersionUID = 8105276695694111976L;
	
	private BackedByComboBox backedByComboBox;
	private final StockChartPanel stockChartPanel;
	
	public IndicatorComboBox(BackedByComboBox backedByComboBox, StockChartPanel stockChartPanel){
		this.backedByComboBox = backedByComboBox;
		this.stockChartPanel = stockChartPanel;
		setOnSelectionCallback(this);
		setModel(new DefaultComboBoxModel(SpringUtil.getBeansOfType(AbstractDisplayableIndicatorConfiguration.class).toArray()));
	}
	
	@Override
	public void onSelection(Object selectedItem){
		AbstractDisplayableIndicatorConfiguration indicatorDisplay = (AbstractDisplayableIndicatorConfiguration)getSelectedItem();
		indicatorDisplay = SpringUtil.getApplicationContext().getBean(indicatorDisplay.getClass());
		if(backedByComboBox.getSelectedIndex() != -1){
			indicatorDisplay.setBarValueType((BarValueType)backedByComboBox.getSelectedItem());
		}else{
			indicatorDisplay.setBarValueType(BarValueType.CLOSE);
		}
		
		if(stockChartPanel != null){
			indicatorDisplay.setStockChartPanel(stockChartPanel);
			indicatorDisplay.refreshValues();
			stockChartPanel.getStockChartPanelState().getDisplayableSet().add(indicatorDisplay);
			RepaintStockChartPanelUtil.repaintStockChartPanel(stockChartPanel);
		}
	}

	@Override
	public void refresh() {
		setModel(new DefaultComboBoxModel(SpringUtil.getBeansOfType(AbstractDisplayableIndicatorConfiguration.class).toArray()));
	}

	@Override
	public long getLastRefreshTime() {
		return 0;
	}

	@Override
	public long getRefreshCount() {
		return 0;
	}

	@Override
	public int getOrder() {
		return 0;
	}
}
